package com.gitee.feizns.quickstart.ding.talk.event.contacts;

import com.dingtalk.api.response.OapiRoleGetroleResponse;
import com.dingtalk.open.app.api.GenericEventListener;
import com.dingtalk.open.app.api.message.GenericOpenDingTalkEvent;
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus;
import com.gitee.feizns.quickstart.ding.talk.api.top.api.role.GetRole;
import com.gitee.feizns.quickstart.ding.talk.api.v10.oauth2.AccessToken;
import com.gitee.feizns.quickstart.ding.talk.utils.Utils;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.function.BiConsumer;

/**
 * 角色添加侦听器
 * @author feizns
 * @since 2025/3/24
 */
@RequiredArgsConstructor
public class LabelConfModifyListener implements GenericEventListener {

    /**
     * 访问令牌
     */
    private final AccessToken accessToken;

    /**
     * 处理器
     */
    private final BiConsumer<Long, OapiRoleGetroleResponse.OpenRole> roleHandler;

    /**
     * 处理器
     */
    private final BiConsumer<Long, OapiRoleGetroleResponse.OpenRole> roleGroupHandler;

    @Override
    public EventAckStatus onEvent(GenericOpenDingTalkEvent event) {
        return onEvent(event, accessToken, roleHandler, roleGroupHandler);
    }

    /**
     * 活动
     * @param event 事件
     * @param accessToken 访问令牌
     * @param roleHandler 角色处理程序
     * @param roleGroupHandler 角色组处理程序
     * @return {@link EventAckStatus }
     */
    public static EventAckStatus onEvent(GenericOpenDingTalkEvent event, AccessToken accessToken,
                                         BiConsumer<Long, OapiRoleGetroleResponse.OpenRole> roleHandler,
                                         BiConsumer<Long, OapiRoleGetroleResponse.OpenRole> roleGroupHandler) {
        if ( "label_conf_modify".equals(event.getEventType()) ) {
            List<Long> labelIdList = event.getData().getList("labelIdList", Long.class);
            labelIdList.forEach(labelId -> {
                OapiRoleGetroleResponse.OpenRole role = GetRole.execute(accessToken.get(), labelId);
                if ( role != null ) {
                    if ( Utils.isRoleGroup(role.getGroupId()) )
                        roleGroupHandler.accept(labelId, role);
                    else
                        roleHandler.accept(labelId, role);
                }
            });
        }
        return EventAckStatus.SUCCESS;
    }

}
